import { defineComponent, ref } from 'vue'
import type { UploadFile, UploadRequestOptions } from 'element-plus'
import { ElButton, ElDialog, ElIcon, ElUpload } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { saveAs } from 'file-saver'
import { getToken } from '@/utils/auth'
import request from '@/utils/request'

export default defineComponent({
  props: {
    modelValue: {
      type: Boolean,
    },
  },
  emits: ['update:modelValue', 'onSuccess'],
  setup(props, { emit }) {
    const header = {
      Authorization: `Bearer ${getToken()}`,
      responseType: 'blob',
    }
    const uploading = ref(false)
    const uploadRef = ref<InstanceType<typeof ElUpload>>()
    function handleFileUploadProgress() {
      uploading.value = true
    }
    function handleFileSuccess(response: Blob, file: UploadFile) {
      const blob = new Blob([response])
      const [name, type] = file.name.split('.', 2)
      saveAs(blob, `result_${name}_${Date.now()}.${type}`)
      emit('update:modelValue', false)
      uploading.value = false
      emit('onSuccess')
      uploadRef.value?.handleRemove(file)
    }
    function submitFileForm() {
      uploadRef.value?.submit()
    }
    function upload(options: UploadRequestOptions) {
      const formData = new FormData()
      formData.append(options.filename, options.file)

      return request({
        method: 'post',
        url: options.action,
        headers: { ...options.headers as Record<string, string>, 'Content-Type': 'multipart/form-data' },
        responseType: 'blob',
        data: formData,
      })
    }
    const downloadTemplate = () => {
      const link = document.createElement('a')
      link.href = '/src/assets/files/学工导入模板.xlsx'
      link.download = '学工导入模版.xlsx'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }

    return () => (
      <ElDialog
        modelValue={props.modelValue}
        onUpdate:modelValue={value => emit('update:modelValue', value)}
        title="导入数据"
        width="600px"
        append-to-body
      >
        {{
          default: () => (
            <ElUpload
              ref={uploadRef}
              limit={1}
              accept=".xlsx, .xls"
              headers={header}
              action="/system/infor/importData"
              disabled={uploading.value}
              on-progress={handleFileUploadProgress}
              on-success={handleFileSuccess}
              auto-upload={false}
              drag
              httpRequest={upload}
              v-slots={{
                default: () => (
                  <>
                    <ElIcon class="el-icon--upload">
                      <UploadFilled />
                    </ElIcon>
                    <div class="el-upload__text">
                      将文件拖到此处，或
                      <em>点击上传</em>
                    </div>
                  </>
                ),
                tip: () => (
                  <div class="el-upload__tip text-center">
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <p>
                      <a class="text-blue-500" href="javascript:;" onClick={downloadTemplate}>下载模板</a>
                    </p>
                  </div>
 
                ),
              }}
            />
          ),
          footer: () => (
            <>
              <div class="dialog-footer">
                <ElButton type="primary" onClick={submitFileForm}>
                  确 定
                </ElButton>
                <ElButton onClick={() => emit('update:modelValue', false)}>
                  取 消
                </ElButton>
              </div>
            </>
          ),
        }}
      </ElDialog>
    )
  },
})
